import 'package:flutter/material.dart';
import 'package:flutter_wisave/Tools/NetworkService.dart';
import 'package:flutter_wisave/widgets/indicator.dart';
import 'package:flutter_wisave/widgets/lineChartSample.dart';
import 'package:flutter_wisave/widgets/lineChartSampleZhe.dart';
import 'package:flutter_wisave/widgets/lineChartSampleZhe1.dart';
import 'package:flutter_wisave/widgets/LineChartResidual.dart';
import '../../Tools/ToolsLocalStorage.dart';
import '../../widgets/AppColors.dart';
import '../Energy/WorkViewDetail.dart';
import '../Energy/WorkBreathViewDetail.dart';
import '../Energy/WorkViewStressDetail.dart';

class WorkView extends StatefulWidget {
  const WorkView({super.key});

  @override
  _WorkViewState createState() => _WorkViewState();
}

class _WorkViewState extends State<WorkView> {
  final NetworkService _networkService = NetworkService();

  List<dynamic> listData = [];
  late List<String> xTitle = [];

  @override
  void initState() {
    super.initState();
    _loadData();
  }

  Future<void> _loadData() async {
    try {
      final result = await _fetchLoadData();
      if (result['code'] == 200 && result['rows'] != null) {
        setState(() {
          // listData = (result['rows'] as List)
          //     .map((item) => (item as Map<String, dynamic>))
          //     .toList();

          listData = (result['rows'] as List)
              .map((item) => (item as Map<String, dynamic>))
              .toList()
              .fold<List<Map<String, dynamic>>>([], (acc, item) {
            if (!acc
                .any((element) => element['timeStamp'] == item['timeStamp'])) {
              acc.add(item);
            }
            return acc;
          })
            ..take(6).toList();

          xTitle = listData.map((item) {
            // DateTime date = DateTime.parse(item['timeStamp']);
            // return '${date.month}.${date.day}';
            return item['timeStamp'].toString();
          }).toList();
        });
      }
    } catch (e) {
      print('Error in _loadData: $e');
    }
  }

  Future<Map<String, dynamic>> _fetchLoadData() async {
    final deptID = await LocalStorage.getstr('deptId');
    try {
      final response = await _networkService
          .get('/plcTimer/procedurevalue2hour/hourInfo?companyId=103');
      // '/plcTimer/procedurevalue2day/dayInfo?companyId=103&startDate=2024-10'); ////formattedDate //deptID
      if (response.statusCode == 200) {
        return response.data;
      } else {
        throw Exception('oxidationloss/avgInfo Failed to load data');
      }
    } catch (e) {
      print('oxidationloss/avgInfo Error in _fetchData: $e');
      rethrow;
    }
  }

  @override
  Widget build(BuildContext context) {
    // 获取屏幕的宽度和高度
    final mediaQuery = MediaQuery.of(context);
    final screenWidth = mediaQuery.size.width;

    return Container(
      padding: const EdgeInsets.all(15.0),
      margin: const EdgeInsets.symmetric(vertical: 4.0, horizontal: 8.0),
      decoration: const BoxDecoration(
        color: Colors.transparent,
      ),
      child: Column(
        children: [
          Padding(
            padding: const EdgeInsets.only(top: 10),
            child: Container(
              padding: EdgeInsets.all(16.0),
              decoration: BoxDecoration(
                color: AppColors.cardColor,
                borderRadius: BorderRadius.circular(8.0),
                boxShadow: [
                  BoxShadow(
                    color: Colors.grey.withOpacity(0.2),
                    blurRadius: 6.0,
                  ),
                ],
              ),
              child: Stack(
                children: [
                  Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Row(
                        children: [
                          Text(
                            '炉温趋势（℃）',
                            style: TextStyle(
                                fontSize: 16,
                                fontWeight: FontWeight.bold,
                                color: AppColors.textPrimary),
                          ),
                          Expanded(child: Container()),
                          GestureDetector(
                            onTap: () {
                              Navigator.push(
                                context,
                                MaterialPageRoute(
                                  builder: (context) => WorkViewDetail(
                                    typeValue: 0,
                                  ),
                                ),
                              );
                            },
                            child: Text(
                              '更多',
                              style: TextStyle(
                                  fontSize: 13,
                                  fontWeight: FontWeight.normal,
                                  color: Color(0xFF2AB6F7)),
                            ),
                          ),
                        ],
                      ),
                      const SizedBox(height: 10.0),
                      Row(
                        children: [
                          Indicator(
                            color: Color(0xFF2AB6F7),
                            text: '上炉温',
                            isSquare: true,
                            size: 12,
                          ),
                          SizedBox(
                            width: 20,
                          ),
                          Indicator(
                            color: Color(0xFFFCAA3F),
                            text: '下炉温',
                            isSquare: true,
                          ),
                          Expanded(child: Container()),
                          Text(
                            '预热段',
                            style: TextStyle(
                                fontSize: 13,
                                fontWeight: FontWeight.normal,
                                color: AppColors.textPrimary),
                          ),
                        ],
                      ),
                      const SizedBox(height: 10),
                      LineChartSampleZhe(
                        xTitle: xTitle,
                        listData: listData.length > 6
                            ? listData.take(6).toList()
                            : listData,
                      ),
                    ],
                  ),
                ],
              ),
            ),
          ),
          SizedBox(height: 10),
          Padding(
            padding: const EdgeInsets.only(top: 10),
            child: Container(
              padding: EdgeInsets.all(16.0),
              decoration: BoxDecoration(
                color: AppColors.cardColor,
                borderRadius: BorderRadius.circular(8.0),
                boxShadow: [
                  BoxShadow(
                    color: Colors.grey.withOpacity(0.2),
                    blurRadius: 6.0,
                  ),
                ],
              ),
              child: Stack(
                children: [
                  Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Row(
                        children: [
                          Text(
                            '炉温趋势（℃）',
                            style: TextStyle(
                                fontSize: 16,
                                fontWeight: FontWeight.bold,
                                color: AppColors.textPrimary),
                          ),
                          Expanded(child: Container()),
                          GestureDetector(
                            onTap: () {
                              Navigator.push(
                                context,
                                MaterialPageRoute(
                                  builder: (context) => WorkViewDetail(
                                    typeValue: 1,
                                  ),
                                ),
                              );
                            },
                            child: Text(
                              '更多',
                              style: TextStyle(
                                  fontSize: 13,
                                  fontWeight: FontWeight.normal,
                                  color: Color(0xFF2AB6F7)),
                            ),
                          ),
                        ],
                      ),
                      const SizedBox(height: 10.0),
                      Row(
                        children: [
                          Indicator(
                            color: Color(0xFF2AB6F7),
                            text: '上炉温',
                            isSquare: true,
                            size: 12,
                          ),
                          SizedBox(
                            width: 20,
                          ),
                          Indicator(
                            color: Color(0xFFFCAA3F),
                            text: '下炉温',
                            isSquare: true,
                          ),
                          Expanded(child: Container()),
                          Text(
                            '加一段',
                            style: TextStyle(
                                fontSize: 13,
                                fontWeight: FontWeight.normal,
                                color: AppColors.textPrimary),
                          ),
                        ],
                      ),
                      const SizedBox(height: 10),
                      LineChartSampleZhe1(
                        xTitle: xTitle,
                        typeValue: 1,
                        listData: listData.length > 6
                            ? listData.take(6).toList()
                            : listData,
                      ),
                    ],
                  ),
                ],
              ),
            ),
          ),
          const SizedBox(height: 10),
          Padding(
            padding: const EdgeInsets.only(top: 10),
            child: Container(
              padding: EdgeInsets.all(16.0),
              decoration: BoxDecoration(
                color: AppColors.cardColor,
                borderRadius: BorderRadius.circular(8.0),
                boxShadow: [
                  BoxShadow(
                    color: Colors.grey.withOpacity(0.2),
                    blurRadius: 6.0,
                  ),
                ],
              ),
              child: Stack(
                children: [
                  Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Row(
                        children: [
                          Text(
                            '炉温趋势（℃）',
                            style: TextStyle(
                                fontSize: 16,
                                fontWeight: FontWeight.bold,
                                color: AppColors.textPrimary),
                          ),
                          Expanded(child: Container()),
                          GestureDetector(
                            onTap: () {
                              Navigator.push(
                                context,
                                MaterialPageRoute(
                                  builder: (context) => WorkViewDetail(
                                    typeValue: 2,
                                  ),
                                ),
                              );
                            },
                            child: Text(
                              '更多',
                              style: TextStyle(
                                  fontSize: 13,
                                  fontWeight: FontWeight.normal,
                                  color: Color(0xFF2AB6F7)),
                            ),
                          ),
                        ],
                      ),
                      const SizedBox(height: 10.0),
                      Row(
                        children: [
                          Indicator(
                            color: Color(0xFF2AB6F7),
                            text: '上炉温',
                            isSquare: true,
                            size: 12,
                          ),
                          SizedBox(
                            width: 20,
                          ),
                          Indicator(
                            color: Color(0xFFFCAA3F),
                            text: '下炉温',
                            isSquare: true,
                          ),
                          Expanded(child: Container()),
                          Text(
                            '加二段',
                            style: TextStyle(
                                fontSize: 13,
                                fontWeight: FontWeight.normal,
                                color: AppColors.textPrimary),
                          ),
                        ],
                      ),
                      const SizedBox(height: 10),
                      LineChartSampleZhe1(
                        xTitle: xTitle,
                        typeValue: 2,
                        listData: listData.length > 6
                            ? listData.take(6).toList()
                            : listData,
                      ),
                    ],
                  ),
                ],
              ),
            ),
          ),
          const SizedBox(height: 10),
          Padding(
            padding: const EdgeInsets.only(top: 10),
            child: Container(
              padding: EdgeInsets.all(16.0),
              decoration: BoxDecoration(
                color: AppColors.cardColor,
                borderRadius: BorderRadius.circular(8.0),
                boxShadow: [
                  BoxShadow(
                    color: Colors.grey.withOpacity(0.2),
                    blurRadius: 6.0,
                  ),
                ],
              ),
              child: Stack(
                children: [
                  Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Row(
                        children: [
                          Text(
                            '残氧量趋势（%）',
                            style: TextStyle(
                                fontSize: 16,
                                fontWeight: FontWeight.bold,
                                color: AppColors.textPrimary),
                          ),
                          Expanded(child: Container()),
                          GestureDetector(
                            onTap: () {
                              Navigator.push(
                                context,
                                MaterialPageRoute(
                                  builder: (context) => WorkBreathViewDetail(),
                                ),
                              );
                            },
                            child: Text(
                              '更多',
                              style: TextStyle(
                                  fontSize: 13,
                                  fontWeight: FontWeight.normal,
                                  color: Color(0xFF2AB6F7)),
                            ),
                          ),
                        ],
                      ),
                      const SizedBox(height: 10.0),
                      Row(
                        children: [
                          Indicator(
                            color: Color(0xFF2AB6F7),
                            text: '预热段',
                            isSquare: true,
                            size: 12,
                          ),
                          SizedBox(
                            width: 20,
                          ),
                          Indicator(
                            color: Color(0xFF814FF3),
                            text: '加一段',
                            isSquare: true,
                            size: 12,
                          ),
                          SizedBox(
                            width: 20,
                          ),
                          Indicator(
                            color: Color(0xFF53E0B1),
                            text: '加二段',
                            isSquare: true,
                            size: 12,
                          ),
                          SizedBox(
                            width: 20,
                          ),
                          Indicator(
                            color: Color(0xFFFCAA3F),
                            text: '均热段',
                            isSquare: true,
                          ),
                        ],
                      ),
                      const SizedBox(height: 10),
                      LineChartResidual(),
                    ],
                  ),
                ],
              ),
            ),
          ),
          const SizedBox(height: 10),
          Padding(
            padding: const EdgeInsets.only(top: 10),
            child: Container(
              padding: EdgeInsets.all(16.0),
              decoration: BoxDecoration(
                color: AppColors.cardColor,
                borderRadius: BorderRadius.circular(8.0),
                boxShadow: [
                  BoxShadow(
                    color: Colors.grey.withOpacity(0.2),
                    blurRadius: 6.0,
                  ),
                ],
              ),
              child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Row(
                      children: [
                        Text(
                          '炉压趋势图 (pa)',
                          style: TextStyle(
                              fontSize: 16,
                              fontWeight: FontWeight.bold,
                              color: AppColors.textPrimary),
                        ),
                        const Expanded(child: SizedBox()),
                        GestureDetector(
                          onTap: () {
                            Navigator.push(
                              context,
                              MaterialPageRoute(
                                builder: (context) => WorkViewStressDetail(),
                              ),
                            );
                          },
                          child: Text(
                            '更多',
                            style: TextStyle(
                                fontSize: 13,
                                fontWeight: FontWeight.normal,
                                color: Color(0xFF2AB6F7)),
                          ),
                        ),
                      ],
                    ),
                    const SizedBox(height: 16.0),
                    const LineChartSample2(
                      spots: [20, 40, 90, 30, 80, 20],
                      xTitle: [
                        '12:00',
                        '12:20',
                        '12:40',
                        '1:00',
                        '1:20',
                        '1:40'
                      ], // 传递 xTitle 数据
                    ),
                  ]),
            ),
          ),
        ],
      ),
    );
  }
}
